package com.dhb.base.util;

import java.util.Random;

public class RandomUtil {
	private static Random random = new Random(System.currentTimeMillis() + new Object().hashCode());
	
	private static char[] CODE = {'0','1','2','3','4','5','6','7','8','9',
					'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
					'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
	
	private static char[] NUM_CODE = {'0','1','2','3','4','5','6','7','8','9'};

	/**
	 * 生成随机字符串,范围[0-9a-zA-Z]
	 * @param length 位数
	 * @return
	 */
	public static String ramdomString(int length) {
		
		
		char[] str = new char[length];
		
		for(int i = 0; i < length; i++) {
			str[i] = CODE[random.nextInt(CODE.length)];
		}
		
		return new String(str);	
		
	}
	

	/**
	 * 生成随机字符串,范围[0-9]
	 * @param length 位数
	 * @return
	 */
	public static String ramdomNumString(int length) {
		char[] str = new char[length];
		
		for(int i = 0; i < length; i++) {
			str[i] = NUM_CODE[random.nextInt(NUM_CODE.length)];
		}
		
		return new String(str);	
	}
	

	public static String randomNum(int length) {
		String no = "";
		// 默认数组中可以选择的部分长度
		int canBeUsed = 10;
		// 初始化备选数组
		int[] defaultNums = new int[canBeUsed];
		for (int i = 0; i < defaultNums.length; i++) {
			defaultNums[i] = i;
		}
		Random random = new Random();
		int[] nums = new int[length];
		// 填充目标数组
		for (int i = 0; i < nums.length; i++) {
			// 将随机选取的数字存入目标数组
			int index = random.nextInt(canBeUsed);
			nums[i] = defaultNums[index];
			// 将已用过的数字扔到备选数组最后，并减小可选区域
			swap(index, canBeUsed - 1, defaultNums);
			canBeUsed--;
		}
		if (nums.length > 0) {
			for (int i = 0; i < nums.length; i++) {
				no += nums[i];
			}
		}

		return no;
	}

	private static void swap(int i, int j, int[] nums) {
		int temp = nums[i];
		nums[i] = nums[j];
		nums[j] = temp;
	}
	
	public static void main(String[] args) {
		for(int i=0 ;i<100;i++){
			System.out.println(RandomUtil.ramdomNumString(6));
		}
	}
}
